﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SqlSugar;
using System.IO;

namespace CodeGenerator
{
    public partial class frmMain : UIForm
    {
        /// <summary>
        /// 全局变量  数据库连接串
        /// </summary>
        public string DbConnectionString;
        /// <summary>
        /// 数据库名称
        /// </summary>
        public string DbName;
        /// <summary>
        /// 表名称
        /// </summary>
        public string TbName;
        /// <summary>
        /// 实体名称（类名称）
        /// </summary>
        public string EntityName;
        /// <summary>
        /// 类名称 生成其他文件使用
        /// </summary>
        public string ClassNames;


        public frmMain()
        {
            InitializeComponent();
        }
        
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMain_Load(object sender, EventArgs e)
        {
            try
            {
                #region 按钮隐藏
                this.btn_Entity.Visible = false;
                this.btn_Service.Visible = false;
                this.btn_ApiController.Visible = false;
                this.chb_IsGenerateAll.Visible = false;
                #endregion

                #region 使用教程说明
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("使用教程");
                sb.AppendLine("① 使用之前请先改代码，改成自己的项目路径，否则路径不对，会报异常");
                sb.AppendLine("② 点击连接数据库，加载所有数据库名");
                sb.AppendLine("③ 选中数据库名称，加载所属表名称");
                sb.AppendLine("④ 选中表名称后，依次点击实体模型、服务实现、Api控制器按钮即可");
                sb.AppendLine("⑤ 当勾选了《生成所有表实体》后，会在指定目录下生成实体，但不可预览");
                sb.AppendLine();
                sb.AppendLine("注：如若在左侧切换了数据库/表，则需要重复第③步的操作，方可继续生成");

                this.rtb_CodeView.Text = sb.ToString();
                #endregion
            }
            catch (Exception ex)
            {
                ShowWarningDialog(ex.Message);
            }
            
        }

        /// <summary>
        /// 选中/未选中操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chb_IsGenerateAll_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                //选中状态下 隐藏掉除实体模型之外的按钮
                if (chb_IsGenerateAll.Checked == true)
                {
                    this.btn_Service.Visible = false;
                    this.btn_ApiController.Visible = false;
                }
                //未选中 则显示
                else
                {
                    this.btn_Service.Visible = true;
                    this.btn_ApiController.Visible = true;
                }
            }
            catch (Exception ex)
            {
                ShowWarningDialog(ex.Message);
            }
            
        }

        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_LinkDb_Click(object sender, EventArgs e)
        {
            try
            {
                //数据库连接
                SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = this.txt_DbStr.Text.ToString().Trim() + "database=master",//连接符字串
                    DbType = SqlSugar.DbType.SqlServer, //数据库类型
                    IsAutoCloseConnection = true //不设成true要手动close
                });

                //查找到所有数据库
                string strSql = @"SELECT TOP 100000 NAME FROM MASTER..SYSDATABASES ORDER BY NAME";
                var dt = db.Ado.GetDataTable(strSql);
                //绑定数据库名称 到ListBox
                this.lb_LKDbs.DataSource = dt;
                this.lb_LKDbs.DisplayMember = "NAME";

                #region 按钮显示
                this.btn_Entity.Visible = true;
                this.btn_Service.Visible = true;
                this.btn_ApiController.Visible = true;
                this.chb_IsGenerateAll.Visible = true;
                #endregion
            }
            catch (Exception ex)
            {
                ShowWarningDialog(ex.Message);
            }           
        }        

        /// <summary>
        /// 选中的数据库名字发生变化后  表名称ListBox也跟着变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lb_LKDbs_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                string dbname = string.Empty;

                //获取选中的数据库名字
                DataRowView dr = lb_LKDbs.Items[this.lb_LKDbs.SelectedIndex] as DataRowView;
                for (int i = 0; i < dr.Row.ItemArray.Length; i++)
                {
                    dbname = dr.Row[i].ToString();
                    this.lab_DbName.Text = dbname;
                    DbName = dbname;
                }
                //数据库连接
                SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = this.txt_DbStr.Text.ToString().Trim() + "database=" + dbname,//连接符字串
                    DbType = SqlSugar.DbType.SqlServer, //数据库类型
                    IsAutoCloseConnection = true //不设成true要手动close
                });
                DbConnectionString = this.txt_DbStr.Text.ToString().Trim() + "database=" + dbname;

                //查找选中的数据库名称下的所属表名称
                string strSql = @"SELECT TOP 100000 NAME FROM SYSOBJECTS WHERE TYPE='U' ORDER BY NAME";
                var dt = db.Ado.GetDataTable(strSql);
                //绑定表名称 到ListBox
                lb_Tbs.DataSource = dt;
                lb_Tbs.DisplayMember = "NAME";
            }
            catch (Exception ex)
            {
                ShowWarningDialog(ex.Message);
            }                       
        }

        /// <summary>
        /// 根据选中的表名称 RichBox动态展示不同代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lb_Tbs_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                string tbname = string.Empty;

                if (lb_Tbs.SelectedItems.Count > 0)
                {
                    DataRowView tbdr = lb_Tbs.Items[this.lb_Tbs.SelectedIndex] as DataRowView;

                    for (int i = 0; i < tbdr.Row.ItemArray.Length; i++)
                    {
                        tbname = tbdr.Row[i].ToString();
                        this.lab_TbName.Text = tbname;
                        TbName = tbname;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowWarningDialog(ex.Message);
            }                       
        }
        
        /// <summary>
        /// 实体模型 代码生成预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Entity_Click(object sender, EventArgs e)
        {
            try
            {
                //数据库连接
                SqlSugarClient SugarClient = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = DbConnectionString,//连接符字串
                    DbType = SqlSugar.DbType.SqlServer, //数据库类型
                    IsAutoCloseConnection = true //不设成true要手动close
                });

                //指定存放路径
                string classPath = @"C:\Entity\";
                //命名空间
                string nameSpace = "WucCloud.Entity";

                //判断是否选中 如果选中生成所有表 反之生成单个表
                if (this.chb_IsGenerateAll.Checked == true)
                {
                    //格式化类名称
                    foreach (var item in SugarClient.DbMaintenance.GetTableInfoList())
                    {
                        if (item.Name.Contains("_"))
                        {
                            var tb = item.Name.Split('_');
                            var entityName = tb[1] + "Entity";
                            SugarClient.MappingTables.Add(entityName, item.Name);
                            EntityName = entityName;
                        }
                        else
                        {
                            var entityName = item.Name + "Entity";
                            SugarClient.MappingTables.Add(entityName, item.Name);
                            EntityName = entityName;
                        }
                    }

                    //生成所有实体  到指定文件夹中
                    SugarClient.DbFirst
                        .IsCreateAttribute(true)
                        .CreateClassFile(classPath, nameSpace);
                    this.rtb_CodeView.Text = "已生成，请到指定目录下查看";
                }
                else
                {
                    //格式化类名称
                    foreach (var item in SugarClient.DbMaintenance.GetTableInfoList())
                    {
                        if (TbName.Contains("_"))
                        {
                            var tb = TbName.Split('_');
                            var entityName = tb[1] + "Entity";
                            SugarClient.MappingTables.Add(entityName, TbName);
                            EntityName = entityName;
                            ClassNames = tb[1];
                        }
                        else
                        {
                            var entityName = TbName + "Entity";
                            SugarClient.MappingTables.Add(entityName, TbName);
                            EntityName = entityName;
                            ClassNames = TbName;
                        }
                    }

                    //生成指定实体  到指定文件夹中
                    SugarClient.DbFirst.Where(TbName)
                        .IsCreateAttribute(true)
                        .IsCreateAttribute().CreateClassFile(classPath, nameSpace);

                    //将读取到的文件内容 反写到RichBox上
                    this.rtb_CodeView.Text = File.ReadAllText(@"" + classPath + "\\" + EntityName + ".cs", Encoding.UTF8);
                }
            }
            catch (Exception ex)
            {
                ShowWarningDialog(ex.Message);
            }
                      
        }

        /// <summary>
        /// 服务实现 代码生成预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Service_Click(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("using SqlSugar;");
                sb.AppendLine("using System;");
                sb.AppendLine("using System.Collections.Generic;");
                sb.AppendLine("using System.Linq;");
                sb.AppendLine("using System.Text;");
                sb.AppendLine("using System.Threading.Tasks;");
                sb.AppendLine("using WucCloud.Entity;");
                sb.AppendLine("using WucCloud.Database;");
                sb.AppendLine("using WucCloud.Utility;");
                sb.AppendLine();
                sb.AppendLine("namespace WucCloud.Application");
                sb.AppendLine("{");
                sb.AppendLine("     /// <summary>");
                sb.AppendLine("     /// XX服务");
                sb.AppendLine("     /// </summary>");
                sb.AppendLine("     public class " + ClassNames + "Service" + " : BaseService" + "<" + EntityName + ">" + ", IDependency");
                sb.AppendLine("     {");
                sb.AppendLine("         public " + ClassNames + "Service(" + "I" + ClassNames + "Repository" + "<" + EntityName + "> " + ClassNames.ToLower() + "Repository,IUnitOfWork unitOfWork)");
                sb.AppendLine("         {");
                sb.AppendLine("             base._repository = " + ClassNames.ToLower() + "Repository;");
                sb.AppendLine("             base._unitOfWork = unitOfWork;");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         #region 获取数据");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 通过Id查询");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyId'>主键Id</param>");
                sb.AppendLine("         /// <returns></returns>");
                sb.AppendLine("         public async Task<" + ClassNames + ">" + " FindById(string keyId)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 var entity = await _repository.FindByIdAsync(keyId);");
                sb.AppendLine("                 return entity;");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 throw new Exception(ex.Message.ToString());");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 自定义条件查询");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyvalue'>查询条件(编码/名称)</param>");
                sb.AppendLine("         /// <returns></returns>");
                sb.AppendLine("         public async Task<List<" + ClassNames + ">>" + " GetList(string keyvalue)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 var entity = await _repository.QueryableAsync(t => t.IsEnabled == true && t.IsDeleted == false);");
                sb.AppendLine();
                sb.AppendLine("                 //条件查询 根据编码/名称查询");
                sb.AppendLine("                 if (!string.IsNullOrEmpty(keyvalue))");
                sb.AppendLine("                 {");
                sb.AppendLine("                     //此处需修改");
                sb.AppendLine("                     entity = entity.FindAll(t => t.EnCode.Contains(keyvalue) || t.RealName.Contains(keyvalue));");
                sb.AppendLine("                 }");
                sb.AppendLine("                 return entity;");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 throw new Exception(ex.Message.ToString());");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 自定义条件分页查询");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyvalue'>查询条件(编码/角色名称)</param>");
                sb.AppendLine("         /// <param name='page'>分页组件类</param>");
                sb.AppendLine("         /// <returns></returns>");
                sb.AppendLine("         public async Task<List<" + ClassNames + ">>" + " QueryPagedList(string keyvalue, PageModel page)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 //获取分页数据");
                sb.AppendLine("                 var entity = await _repository.SugarQueryable()");
                sb.AppendLine("                 .Where(t => t.IsEnabled == true && t.IsDeleted == false)");
                sb.AppendLine("                 .ToOffsetPageAsync(page.PageIndex, page.PageSize);");
                sb.AppendLine();
                sb.AppendLine("                 //条件查询 根据编码/名称查询");
                sb.AppendLine("                 if (!string.IsNullOrEmpty(keyvalue))");
                sb.AppendLine("                 {");
                sb.AppendLine("                     //此处需修改");
                sb.AppendLine("                     entity = entity.FindAll(t => t.EnCode.Contains(keyvalue) || t.RealName.Contains(keyvalue));");
                sb.AppendLine("                 }");
                sb.AppendLine("                 return entity;");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 throw new Exception(ex.Message.ToString());");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine("         #endregion");
                sb.AppendLine();
                sb.AppendLine("         #region 提交数据");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 保存数据（新增/编辑）");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyId'>主键Id</param>");
                sb.AppendLine("         /// <param name='entity'>实体信息</param>");
                sb.AppendLine("         /// <returns></returns>");
                sb.AppendLine("         public async Task<bool> SaveChange(string keyId," + ClassNames + "entity");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 //新增");
                sb.AppendLine("                 if (string.IsNullOrEmpty(keyId))");
                sb.AppendLine("                 {");
                sb.AppendLine("                     #region 数据校验 此处需修改，视情况而定 可删除");
                sb.AppendLine("                     //重复校验");
                sb.AppendLine("                     var data = await _repository.AnyAsync(t => t.AccountName == entity.AccountName);");
                sb.AppendLine("                     if (data == true)");
                sb.AppendLine("                     {");
                sb.AppendLine("                     }");
                sb.AppendLine("                     //非空校验");
                sb.AppendLine("                     if (string.IsNullOrEmpty(entity.EnCode) || string.IsNullOrEmpty(entity.AccountName) || string.IsNullOrEmpty(entity.Password) || string.IsNullOrEmpty(entity.RealName) || string.IsNullOrEmpty(entity.MobilePhone))");
                sb.AppendLine("                     {");
                sb.AppendLine("                         throw new Exception(编码/账户/密码/真实姓名/手机号不可为空);");
                sb.AppendLine("                     }");
                sb.AppendLine("                     #endregion");
                sb.AppendLine();
                sb.AppendLine("                     //数据初始化");
                sb.AppendLine("                     entity.KeyId = ContinuityGUID.CreateGuid().ToString();");
                sb.AppendLine("                     entity.IsEnabled = true;");
                sb.AppendLine("                     entity.IsDeleted = false;");
                sb.AppendLine("                     entity.CreateTime = DateTime.Now;");
                sb.AppendLine("                     entity.CreateUserId = GlobalContext.CurrentUser().KeyId;");
                sb.AppendLine("                     entity.CreateUserName = GlobalContext.CurrentUser().RealName;");
                sb.AppendLine();
                sb.AppendLine("                     return await _repository.InsertAsync(entity);");
                sb.AppendLine("                 }");
                sb.AppendLine("                 //编辑");
                sb.AppendLine("                 else");
                sb.AppendLine("                 {");
                sb.AppendLine("                     //数据初始化");
                sb.AppendLine("                     entity.KeyId = ContinuityGUID.CreateGuid().ToString();");
                sb.AppendLine("                     entity.IsEnabled = true;");
                sb.AppendLine("                     entity.IsDeleted = false;");
                sb.AppendLine("                     entity.UpdateTime = DateTime.Now;");
                sb.AppendLine("                     entity.UpdateUserId = GlobalContext.CurrentUser().KeyId;");
                sb.AppendLine("                     entity.UpdateUserName = GlobalContext.CurrentUser().RealName;");
                sb.AppendLine();
                sb.AppendLine("                     return await _repository.UpdateAsync(entity);");
                sb.AppendLine("                     ");
                sb.AppendLine("                 }");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 throw new Exception(ex.Message.ToString());");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 删除");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyId'>主键Id</param>");
                sb.AppendLine("         /// <returns></returns>");
                sb.AppendLine("         public async Task<bool> Deleteable(string keyId)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 bool result = await _repository.DeleteAsync(keyId);");
                sb.AppendLine("                 if (!result)");
                sb.AppendLine("                 {");
                sb.AppendLine("                     throw new Exception('删除失败');");
                sb.AppendLine("                 }");
                sb.AppendLine("                 return result;");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 throw new Exception(ex.Message.ToString());");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 假删（逻辑删除）");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyId'>主键Id</param>");
                sb.AppendLine("         /// <returns></returns>");
                sb.AppendLine("         public async Task<bool> SoftDeleteable(string keyId)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 var data = await _repository.FindByIdAsync(keyId);");
                sb.AppendLine("                 data.IsEnabled = false;");
                sb.AppendLine("                 data.IsDeleted = true;");
                sb.AppendLine("                 bool result = await _repository.UpdateAsync(data);");
                sb.AppendLine("                 if (!result)");
                sb.AppendLine("                 {");
                sb.AppendLine("                     throw new Exception('删除失败');");
                sb.AppendLine("                 }");
                sb.AppendLine("                 return result;");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 throw new Exception(ex.Message.ToString());");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 批量删除");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyIds'>主键Id集合,以英文逗号分隔</param>");
                sb.AppendLine("         /// <returns></returns>");
                sb.AppendLine("         public async Task<bool> BatchDeleteable(string[] keyIds)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 bool result = false;");
                sb.AppendLine("                 //将数组转换为以,分割的字符串");
                sb.AppendLine("                 string Ids = string.Join(', ', keyIds);");
                sb.AppendLine();
                sb.AppendLine("                 foreach (var item in Ids.Split(','))");
                sb.AppendLine("                 {");
                sb.AppendLine("                     result = await _repository.DeleteAsync(item);");
                sb.AppendLine("                 }");
                sb.AppendLine("                 if (!result)");
                sb.AppendLine("                 {");
                sb.AppendLine("                     throw new Exception('删除失败');");
                sb.AppendLine("                 }");
                sb.AppendLine("                 else");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return result;");
                sb.AppendLine("                 }");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 throw new Exception(ex.Message.ToString());");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine("         #endregion");
                sb.AppendLine();
                sb.AppendLine("         #region 拓展");
                sb.AppendLine("         #endregion");
                sb.AppendLine("     }");
                sb.AppendLine("}");

                this.rtb_CodeView.Text = sb.ToString();

                //创建一个新文件，写入指定的字符串，如果文件已存在 则覆盖原文件
                File.WriteAllText(@"C:\Service\" + ClassNames + "Service" + ".cs", sb.ToString());
            }
            catch (Exception ex)
            {
                ShowWarningDialog(ex.Message);
            }            
        }

        /// <summary>
        /// Api控制器 代码生成预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ApiController_Click(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("using Microsoft.AspNetCore.Authorization;");
                sb.AppendLine("using Microsoft.AspNetCore.Mvc;");
                sb.AppendLine("using SqlSugar;");
                sb.AppendLine("using System;");
                sb.AppendLine("using System.ComponentModel.DataAnnotations;");
                sb.AppendLine("using System.Threading.Tasks;");
                sb.AppendLine("using WucCloud.Application;");
                sb.AppendLine("using WucCloud.Entity;");
                sb.AppendLine("using NETCore.Encrypt;");
                sb.AppendLine("using WucCloud.Utility;");
                sb.AppendLine();
                sb.AppendLine("namespace WucCloud.WebApi.Controllers");
                sb.AppendLine("{");
                sb.AppendLine("     /// <summary>");
                sb.AppendLine("     /// XX管理");
                sb.AppendLine("     /// </summary>");
                sb.AppendLine("     [Route('api/[controller]/[action]')]");
                sb.AppendLine("     [Area('SystemManage')]");
                sb.AppendLine("     [Authorize]");
                sb.AppendLine("     public class " + ClassNames + "Controller : ControllerBase");
                sb.AppendLine("     {");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// XX服务类");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         private readonly " + ClassNames + "Service " + "_service;");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 构造函数");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         public " + ClassNames + "Controller(" + ClassNames + "Service " + "service" + ")");
                sb.AppendLine("         {");
                sb.AppendLine("             _service = service;");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         #region 获取数据");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 通过Id查询");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyId'>主键Id</param>");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         [HttpGet]");
                sb.AppendLine("         public async Task<ActionResult<UnifyResult>> FindById([Required] string keyId)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 //通过Id查询数据");
                sb.AppendLine("                 var entity = await _service.FindById(keyId);");
                sb.AppendLine("                 //判断是否获取到数据");
                sb.AppendLine("                 if (entity == null)");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult<dynamic>");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.NoneData,");
                sb.AppendLine("                         Message = ResultCode.NoneData.Description(),");
                sb.AppendLine("                         Data = null,");
                sb.AppendLine("                         TotalCount = 0");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("                 //返回获取到的数据");
                sb.AppendLine("                 else");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult<dynamic>");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Success,");
                sb.AppendLine("                         Message = ResultCode.Success.Description(),");
                sb.AppendLine("                         Data = entity,");
                sb.AppendLine("                         TotalCount = 1");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 return new UnifyResult()");
                sb.AppendLine("                 {");
                sb.AppendLine("                     StatusCode = ResultCode.Error,");
                sb.AppendLine("                     Message = ex.Message.ToString()");
                sb.AppendLine("                 };");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 自定义条件查询");
                sb.AppendLine("         /// </summary>");
                sb.AppendLine("         /// <param name='keyvalue'>查询条件(编码/名称)</param>");
                sb.AppendLine("         /// <returns></returns>");
                sb.AppendLine("         [HttpGet]");
                sb.AppendLine("         public async Task<ActionResult<UnifyResult>> GetList(string keyvalue)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 var entity = await _service.GetList(keyvalue);");
                sb.AppendLine();
                sb.AppendLine("                 //判断是否获取到数据");
                sb.AppendLine("                 if (entity.Count == 0)");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult<dynamic>");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.NoneData,");
                sb.AppendLine("                         Message = ResultCode.NoneData.Description(),");
                sb.AppendLine("                         Data = null,");
                sb.AppendLine("                         TotalCount = 0");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("                 //返回获取到的数据");
                sb.AppendLine("                 else");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult<dynamic>");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Success,");
                sb.AppendLine("                         Message = ResultCode.Success.Description(),");
                sb.AppendLine("                         Data = entity,");
                sb.AppendLine("                         TotalCount = entity.Count");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 return new UnifyResult()");
                sb.AppendLine("                 {");
                sb.AppendLine("                     StatusCode = ResultCode.Error,");
                sb.AppendLine("                     Message = ex.Message.ToString()");
                sb.AppendLine("                 };");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 自定义条件分页查询");
                sb.AppendLine("         /// </summary>");
                sb.AppendLine("         /// <param name='keyvalue'>查询条件（编码/名称）</param>");
                sb.AppendLine("         /// <param name='pageIndex'>页数</param>");
                sb.AppendLine("         /// <param name='pageSize'>行数</param>");
                sb.AppendLine("         /// <returns></returns>");
                sb.AppendLine("         [HttpGet]");
                sb.AppendLine("         public async Task<ActionResult<UnifyResult>> QueryPagedList(string keyvalue, [Required] int pageIndex, [Required] int pageSize)");
                sb.AppendLine("         {");
                sb.AppendLine("             //分页组件类");
                sb.AppendLine("             PageModel page = new PageModel");
                sb.AppendLine("             {");
                sb.AppendLine("                 PageIndex = pageIndex,");
                sb.AppendLine("                 PageSize = pageSize");
                sb.AppendLine("             };");
                sb.AppendLine();
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 //获取分页数据");
                sb.AppendLine("                 var entity = await _service.QueryPagedList(keyvalue, page);");
                sb.AppendLine();
                sb.AppendLine("                 //判断是否获取到数据");
                sb.AppendLine("                 if (entity.Count == 0)");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult<dynamic>");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.NoneData,");
                sb.AppendLine("                         Message = ResultCode.NoneData.Description(),");
                sb.AppendLine("                         Data = null,");
                sb.AppendLine("                         TotalCount = 0");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("                 //返回获取到的数据");
                sb.AppendLine("                 else");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult<dynamic>");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Success,");
                sb.AppendLine("                         Message = ResultCode.Success.Description(),");
                sb.AppendLine("                         Data = entity,");
                sb.AppendLine("                         TotalCount = entity.Count");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 return new UnifyResult()");
                sb.AppendLine("                 {");
                sb.AppendLine("                     StatusCode = ResultCode.Error,");
                sb.AppendLine("                     Message = ex.Message.ToString()");
                sb.AppendLine("                 };");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine("         #endregion");
                sb.AppendLine();
                sb.AppendLine("         #region 提交数据");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 保存数据（新增/编辑）");
                sb.AppendLine("         /// </summary>");
                sb.AppendLine("         /// <param name='keyId'>主键Id</param>");
                sb.AppendLine("         /// <param name='entity'>实体信息</param>");
                sb.AppendLine("         /// <returns></returns>");
                sb.AppendLine("         [HttpPost]");
                sb.AppendLine("         public async Task<ActionResult<UnifyResult>> SaveChange(string keyId, [FromForm] "+ ClassNames + "Entity" + " entity)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 bool result = await _service.SaveChange(keyId, entity);");
                sb.AppendLine("                 //操作失败");
                sb.AppendLine("                 if (!result)");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult()");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Failed,");
                sb.AppendLine("                         Message = ResultCode.Failed.Description()");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("                 //操作成功");
                sb.AppendLine("                 else");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult()");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Success,");
                sb.AppendLine("                         Message = ResultCode.Success.Description()");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 return new UnifyResult()");
                sb.AppendLine("                 {");
                sb.AppendLine("                     StatusCode = ResultCode.Error,");
                sb.AppendLine("                     Message = ex.Message.ToString()");
                sb.AppendLine("                 };");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 删除");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyId'>主键Id</param>");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         [HttpDelete]");
                sb.AppendLine("         public async Task<ActionResult<UnifyResult>> Deleteable([Required] string keyId)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 bool result = await _service.Deleteable(keyId);");
                sb.AppendLine("                 //操作失败");
                sb.AppendLine("                 if (!result)");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult()");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Failed,");
                sb.AppendLine("                         Message = ResultCode.Failed.Description()");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("                 //操作成功");
                sb.AppendLine("                 else");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult()");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Success,");
                sb.AppendLine("                         Message = ResultCode.Success.Description()");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 return new UnifyResult()");
                sb.AppendLine("                 {");
                sb.AppendLine("                     StatusCode = ResultCode.Error,");
                sb.AppendLine("                     Message = ex.Message.ToString()");
                sb.AppendLine("                 };");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 假删（逻辑删除）");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyId'>主键Id</param>");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         [HttpDelete]");
                sb.AppendLine("         public async Task<ActionResult<UnifyResult>> SoftDeleteable([Required] string keyId)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 bool result = await _service.SoftDeleteable(keyId);");
                sb.AppendLine("                 //操作失败");
                sb.AppendLine("                 if (!result)");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult()");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Failed,");
                sb.AppendLine("                         Message = ResultCode.Failed.Description()");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("                 //操作成功");
                sb.AppendLine("                 else");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult()");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Success,");
                sb.AppendLine("                         Message = ResultCode.Success.Description()");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 return new UnifyResult()");
                sb.AppendLine("                 {");
                sb.AppendLine("                     StatusCode = ResultCode.Error,");
                sb.AppendLine("                     Message = ex.Message.ToString()");
                sb.AppendLine("                 };");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine();
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// 批量删除");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         /// <param name='keyIds'>主键Id集合,以英文逗号分隔</param>");
                sb.AppendLine("         /// <summary>");
                sb.AppendLine("         [HttpDelete]");
                sb.AppendLine("         public async Task<ActionResult<UnifyResult>> BatchDeleteable([Required] string[] keyIds)");
                sb.AppendLine("         {");
                sb.AppendLine("             try");
                sb.AppendLine("             {");
                sb.AppendLine("                 bool result = await _service.BatchDeleteable(keyIds);");
                sb.AppendLine("                 //操作失败");
                sb.AppendLine("                 if (!result)");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult()");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Failed,");
                sb.AppendLine("                         Message = ResultCode.Failed.Description()");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("                 //操作成功");
                sb.AppendLine("                 else");
                sb.AppendLine("                 {");
                sb.AppendLine("                     return new UnifyResult()");
                sb.AppendLine("                     {");
                sb.AppendLine("                         StatusCode = ResultCode.Success,");
                sb.AppendLine("                         Message = ResultCode.Success.Description()");
                sb.AppendLine("                     };");
                sb.AppendLine("                 }");
                sb.AppendLine("             }");
                sb.AppendLine("             catch(Exception ex)");
                sb.AppendLine("             {");
                sb.AppendLine("                 return new UnifyResult()");
                sb.AppendLine("                 {");
                sb.AppendLine("                     StatusCode = ResultCode.Error,");
                sb.AppendLine("                     Message = ex.Message.ToString()");
                sb.AppendLine("                 };");
                sb.AppendLine("             }");
                sb.AppendLine("         }");
                sb.AppendLine("         #endregion");
                sb.AppendLine("     }");
                sb.AppendLine("}");

                this.rtb_CodeView.Text = sb.ToString();

                //创建一个新文件，写入指定的字符串，如果文件已存在 则覆盖原文件
                File.WriteAllText(@"C:\Controller\" + ClassNames + "Controller" + ".cs", sb.ToString());
            }
            catch (Exception ex)
            {
                ShowWarningDialog(ex.Message);
            }            
        }
    }
}
